package controlador.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Clase usada para leer y escribir la configuracion en ficheros.
 * @author Globex Inc.
 *
 */
public class Config {
	
	/**
	 * Lee la configuraci&oacute;n almacenada en un fichero dado.
	 * @param ruta Ruta del fichero.
	 * @return Un HashMap&lt;String, String&gt; con la configuraci&oacute;n leida.
	 */
	public static HashMap<String, String> read(String ruta) {
		HashMap<String, String> conf = new HashMap<String, String>();
		
		try {
			BufferedReader reader = new BufferedReader(new FileReader(ruta));
			
			String line;
			while((line = reader.readLine()) != null) {
				line = line.trim();
				if(!(line.startsWith("#") || line.isEmpty())) {
					String[] pair = line.split("=");
					conf.put(pair[0].trim(), pair[1].trim());
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return conf;
	}
	
	/**
	 * Escribe una configuraci&oacute;n dada en un fichero.
	 * @param conf La configuraci&oacute;n a escribir.
	 * @param ruta La ruta del fichero donde se debe escribir la configuraci&oacute;
	 */
	public static void write(HashMap<String, String> conf, String ruta){
		try {
			BufferedWriter writer = new BufferedWriter(new FileWriter(ruta));
			
			Set set = conf.entrySet();
			Iterator i = set.iterator();
			
			while (i.hasNext()){
				Map.Entry me = (Map.Entry)i.next();
				//System.out.println(me.getKey() + " = " + me.getValue() );
				writer.write(me.getKey()+" = "+me.getValue()+"\n");
				writer.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
